<template>
    <div class="multi-image-upload">
        <!-- 图片列表 -->
        <div class="image-list">
            <div v-for="(image, index) in imageList" :key="index" class="image-item"
                :class="{ 'dragging': draggingIndex === index }" draggable="true"
                @dragstart="onDragStart(index, $event)" @dragover.prevent @drop="onDrop(index, $event)"
                @dragenter.prevent>
                <img :src="image.url" :alt="image.name" class="image-preview" />
                <!-- 删除按钮 - 右上角 -->
                <div class="delete-button" @click="removeImage(index)">
                    <i class="el-icon-close"></i>
                </div>

                <!-- 操作按钮 - 鼠标悬停时显示 -->
                <div class="image-overlay">
                    <div class="image-actions">
                        <el-button type="primary" size="small" circle @click="previewImage(image)" class="preview-btn">
                            <i class="el-icon-zoom-in"></i>
                        </el-button>
                    </div>
                </div>
                <div class="image-name">{{ image.name }}</div>
            </div>

            <!-- 上传按钮 -->
            <div v-if="imageList.length < maxCount" class="upload-item">
                <input ref="fileInput" type="file" :accept="accept" :multiple="multiple" style="display: none;"
                    @change="handleFileChange" />
                <div class="upload-content" @click="triggerFileSelect" style="cursor: pointer;">
                    <i class="el-icon-plus upload-icon"></i>
                    <div class="upload-text">{{ uploadText }}</div>
                </div>
            </div>
        </div>

        <!-- 图片预览对话框 -->
        <el-dialog v-model="previewVisible" title="图片预览" width="60%" center>
            <div class="preview-container">
                <img :src="previewImageUrl" class="preview-image" />
            </div>
        </el-dialog>

        <!-- 上传进度 -->
        <el-progress v-if="uploadProgress > 0 && uploadProgress < 100" :percentage="uploadProgress" :stroke-width="4"
            class="upload-progress" />
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { handleElementUpload, uploadImage, deleteImage } from '@/utils/uploadHelper';

interface ImageItem {
    url: string;
    name: string;
    file?: File;
}

interface Props {
    modelValue?: string[]; // 图片URL数组
    maxCount?: number; // 最大上传数量
    multiple?: boolean; // 是否支持多选
    accept?: string; // 接受的文件类型
    uploadText?: string; // 上传按钮文字
    disabled?: boolean; // 是否禁用
    traceabilityId?: number; // 溯源记录ID
    fieldType?: string; // 字段类型：'certificate'(动检证), 'enterprise'(企业照片), 默认(产品检验报告)
}

interface Emits {
    (e: 'update:modelValue', value: string[]): void;
    (e: 'change', value: string[]): void;
    (e: 'remove', index: number, image: ImageItem): void;
    (e: 'upload-success', image: ImageItem): void;
    (e: 'upload-error', error: Error): void;
}

const props = withDefaults(defineProps<Props>(), {
    modelValue: () => [],
    maxCount: 10,
    multiple: true,
    accept: 'image/*',
    uploadText: '点击上传',
    disabled: false
});

const emit = defineEmits<Emits>();

// 响应式数据
const imageList = ref<ImageItem[]>([]);
const fileInput = ref<HTMLInputElement>();
const previewVisible = ref(false);
const previewImageUrl = ref('');
const uploadProgress = ref(0);
const draggingIndex = ref(-1);

// 监听外部传入的图片URL数组变化
watch(() => props.modelValue, (newValue) => {
    console.log('MultiImageUpload watch 触发，新值:', newValue);

    if (newValue && Array.isArray(newValue) && newValue.length > 0) {
        const newImageList = newValue.map((url, index) => ({
            url,
            name: `图片${index + 1}`
        }));

        console.log('更新图片列表:', newImageList);
        imageList.value = newImageList;
    } else {
        // 处理空值、非数组或空数组的情况
        console.log('清空图片列表');
        imageList.value = [];
    }
}, { immediate: true, deep: true });

// 监听图片列表变化，向外部发送更新
watch(imageList, (newValue) => {
    const urls = newValue.map(item => item.url);
    const currentModelValue = props.modelValue || [];

    console.log('imageList变化，新值:', urls);
    console.log('当前modelValue:', currentModelValue);

    // 避免无限循环：只有当值真正不同时才发送更新
    if (JSON.stringify(urls) !== JSON.stringify(currentModelValue)) {
        console.log('发送更新到父组件:', urls);
        emit('update:modelValue', urls);
        emit('change', urls);
    } else {
        console.log('值相同，不发送更新');
    }
}, { deep: true });



// 触发文件选择
const triggerFileSelect = () => {
    console.log('点击上传按钮');
    console.log('组件状态 - disabled:', props.disabled);
    console.log('组件状态 - traceabilityId:', props.traceabilityId);

    if (props.disabled) {
        console.log('组件已禁用');
        return;
    }

    // 检查traceabilityId是否有效
    if (!props.traceabilityId || props.traceabilityId === 0) {
        ElMessage.error('溯源ID不能为空，请先保存基本信息');
        return;
    }

    console.log('触发文件选择，fileInput:', fileInput.value);
    if (fileInput.value) {
        fileInput.value.click();
        console.log('文件选择器已触发');
    } else {
        console.error('fileInput 元素不存在');
    }
};

// 文件选择处理
const handleFileChange = async (event: Event) => {
    console.log('文件选择事件触发');
    const target = event.target as HTMLInputElement;
    const files = target.files;

    if (!files || files.length === 0) {
        console.log('没有选择文件');
        return;
    }

    console.log('选择了文件:', files.length, '个');

    for (let i = 0; i < files.length; i++) {
        const file = files[i];

        // 检查文件数量限制
        if (imageList.value.length >= props.maxCount) {
            ElMessage.warning(`最多只能上传 ${props.maxCount} 张图片`);
            break;
        }

        // 检查文件类型
        if (!file.type.startsWith('image/')) {
            ElMessage.error('只能上传图片文件');
            continue;
        }

        // 检查文件大小（5MB）
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
            ElMessage.error('图片大小不能超过 5MB');
            continue;
        }

        // 上传文件
        await uploadFile(file);
    }

    // 清空文件输入框
    target.value = '';
};

// 上传单个文件
const uploadFile = async (file: File) => {
    // 再次检查traceabilityId是否有效
    if (!props.traceabilityId || props.traceabilityId === 0) {
        ElMessage.error('溯源ID不能为空，请先保存基本信息');
        return;
    }

    uploadProgress.value = 10;

    try {
        // 使用新的上传工具函数
        const url = await uploadImage(
            file,
            (data, uploadedFile) => {
                console.log('上传成功，数据:', data);
                uploadProgress.value = 100;

                // 适配新的数据结构
                const imageUrl = data.url || data.data?.uploadedUrls?.[0] || '';
                const imageItem: ImageItem = {
                    url: imageUrl,
                    name: uploadedFile.name || `图片${imageList.value.length + 1}`,
                    file: uploadedFile
                };

                console.log('创建图片项:', imageItem);
                imageList.value.push(imageItem);
                emit('upload-success', imageItem);

                setTimeout(() => {
                    uploadProgress.value = 0;
                }, 1000);
            },
            (error) => {
                console.error('上传失败:', error);
                uploadProgress.value = 0;
                emit('upload-error', error);
            },
            props.traceabilityId,
            props.fieldType
        );

        if (!url) {
            throw new Error('上传失败');
        }

    } catch (error) {
        console.error('上传失败:', error);
        uploadProgress.value = 0;
        ElMessage.error('图片上传失败: ' + (error instanceof Error ? error.message : '未知错误'));
        emit('upload-error', error instanceof Error ? error : new Error('上传失败'));
    }
};



// 删除图片
const removeImage = async (index: number) => {
    // 检查traceabilityId是否有效
    if (!props.traceabilityId || props.traceabilityId === 0) {
        ElMessage.error('溯源ID不能为空，请先保存基本信息');
        return;
    }

    try {
        await ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        const removedImage = imageList.value[index];
        console.log('要删除的图片:', removedImage);

        // 调用后端删除接口，传递图片URL
        const deleteSuccess = await deleteImage(props.traceabilityId, props.fieldType, removedImage.url);

        if (deleteSuccess) {
            // 删除成功后，从本地列表中移除
            imageList.value.splice(index, 1);
            console.log('删除成功，从本地列表移除，剩余图片数量:', imageList.value.length);

            // 通知父组件删除事件
            emit('remove', index, removedImage);

            // 更新v-model为剩余的图片URL数组
            const remainingUrls = imageList.value.map(item => item.url);
            console.log('更新v-model，剩余URLs:', remainingUrls);
            emit('update:modelValue', remainingUrls);

            // 显示成功消息
            ElMessage.success('删除成功');

        } else {
            // 删除失败，不更新本地列表
            ElMessage.error('删除失败，请重试');
        }
    } catch {
        // 用户取消删除
    }
};

// 预览图片
const previewImage = (image: ImageItem) => {
    previewImageUrl.value = image.url;
    previewVisible.value = true;
};

// 拖拽排序
const onDragStart = (index: number, event: DragEvent) => {
    draggingIndex.value = index;
    if (event.dataTransfer) {
        event.dataTransfer.effectAllowed = 'move';
        event.dataTransfer.setData('text/html', index.toString());
    }
};

const onDrop = (index: number, event: DragEvent) => {
    event.preventDefault();
    const fromIndex = draggingIndex.value;
    const toIndex = index;

    if (fromIndex !== -1 && fromIndex !== toIndex) {
        const image = imageList.value[fromIndex];
        imageList.value.splice(fromIndex, 1);
        imageList.value.splice(toIndex, 0, image);
    }

    draggingIndex.value = -1;
};

// 暴露方法给父组件
defineExpose({
    clear: () => {
        imageList.value = [];
    },
    getImages: () => imageList.value
});
</script>

<style scoped>
.multi-image-upload {
    width: 100%;
}

.image-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 16px;
    margin-bottom: 16px;
}

.image-item {
    position: relative;
    width: 120px;
    height: 120px;
    border-radius: 8px;
    overflow: hidden;
    border: 2px solid #e4e7ed;
    cursor: move;
    transition: all 0.3s ease;
}

/* 删除按钮样式 */
.delete-button {
    position: absolute;
    top: 4px;
    right: 4px;
    width: 24px;
    height: 24px;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    z-index: 10;
    transition: all 0.3s ease;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.delete-button:hover {
    background: #ff4757;
    color: white;
    transform: scale(1.1);
}

.delete-button i {
    font-size: 14px;
    color: #666;
    transition: color 0.3s ease;
}

.delete-button:hover i {
    color: white;
}

.image-item:hover {
    border-color: #409eff;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.image-item.dragging {
    opacity: 0.5;
    transform: rotate(5deg);
}

.image-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.image-item:hover .image-overlay {
    opacity: 1;
}

.image-actions {
    display: flex;
    gap: 8px;
}

.delete-btn,
.preview-btn {
    width: 32px;
    height: 32px;
    padding: 0;
}

.image-name {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    font-size: 12px;
    padding: 4px 8px;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.upload-item {
    width: 120px;
    height: 120px;
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s ease;
    background: #fafafa;
}

.upload-item:hover {
    border-color: #409eff;
    background: #f0f9ff;
}

.upload-content {
    text-align: center;
    color: #8c939d;
    pointer-events: auto;
    user-select: none;
}

.upload-icon {
    font-size: 28px;
    margin-bottom: 8px;
}

.upload-text {
    font-size: 14px;
}

.preview-container {
    text-align: center;
}

.preview-image {
    max-width: 100%;
    max-height: 60vh;
    object-fit: contain;
}

.upload-progress {
    margin-top: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .image-list {
        grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
        gap: 12px;
    }

    .image-item,
    .upload-item {
        width: 100px;
        height: 100px;
    }

    .delete-button {
        width: 20px;
        height: 20px;
        top: 2px;
        right: 2px;
    }

    .delete-button i {
        font-size: 12px;
    }

    .upload-icon {
        font-size: 24px;
    }

    .upload-text {
        font-size: 12px;
    }
}
</style>